<template>
  <el-dialog
      v-model="dialogVisible"
      :before-close="handleClose"
      class="user-detail-dialog"
      title="用户详情"
      width="800px"
  >
    <div v-loading="loading" class="user-detail">
      <div v-if="userDetail" class="detail-content">
        <!-- 用户头像和基本信息 -->
        <div class="user-header">
          <el-avatar :size="80" :src="userDetail.avatar">
            <el-icon size="40">
              <User/>
            </el-icon>
          </el-avatar>
          <div class="user-basic">
            <h3>{{ userDetail.username }}</h3>
            <p>{{ userDetail.nickname || '未设置昵称' }}</p>
            <el-tag :type="userDetail.status === 1 ? 'success' : 'danger'" size="small">
              {{ userDetail.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="detail-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户ID">
              {{ userDetail.id }}
            </el-descriptions-item>

            <el-descriptions-item label="用户名">
              {{ userDetail.username }}
            </el-descriptions-item>

            <el-descriptions-item label="昵称">
              {{ userDetail.nickname || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="邮箱">
              {{ userDetail.email || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="手机号">
              {{ userDetail.phone || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="性别">
              <el-tag :type="getGenderTagType(userDetail.gender)" size="small">
                {{ getGenderText(userDetail.gender) }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="生日">
              {{ formatDate(userDetail.birthday) || '-' }}
            </el-descriptions-item>

            <el-descriptions-item label="状态">
              <el-tag :type="userDetail.status === 1 ? 'success' : 'danger'" size="small">
                {{ userDetail.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="最后登录时间">
              {{ formatDateTime(userDetail.lastLoginTime) || '-' }}
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="注册时间">
              {{ formatDateTime(userDetail.createTime) }}
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="更新时间">
              {{ formatDateTime(userDetail.updateTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div v-else class="no-data">
        <el-empty description="暂无用户信息"/>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
            v-if="userDetail"
            :type="userDetail.status === 1 ? 'warning' : 'success'"
            @click="handleUpdateStatus"
        >
          {{ userDetail.status === 1 ? '禁用用户' : '启用用户' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {User} from '@element-plus/icons-vue'
import {useUserStore} from '@/store/user'
import {formatDate, formatDateTime} from '@/utils'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userId: {
    type: [Number, String],
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'refresh'])

// 用户Store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const userDetail = computed(() => userStore.currentUser)

// 方法
const handleClose = () => {
  dialogVisible.value = false
  userStore.currentUser = null
}

const loadUserDetail = async () => {
  if (!props.userId) return

  loading.value = true
  try {
    await userStore.getUserDetail(props.userId)
  } catch (error) {
    console.error('加载用户详情失败:', error)
    ElMessage.error('加载用户详情失败')
  } finally {
    loading.value = false
  }
}

const handleUpdateStatus = async () => {
  if (!userDetail.value) return

  const newStatus = userDetail.value.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(
        `确定要${action}用户 "${userDetail.value.username}" 吗？`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await userStore.updateUserStatus(userDetail.value.id, newStatus)
    ElMessage.success(`${action}成功`)

    // 刷新用户详情
    await loadUserDetail()

    // 通知父组件刷新列表
    emit('refresh')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

const getGenderText = (gender) => {
  const map = {0: '未知', 1: '男', 2: '女'}
  return map[gender] || '未知'
}

const getGenderTagType = (gender) => {
  const map = {0: 'info', 1: 'primary', 2: 'success'}
  return map[gender] || 'info'
}

// 监听器
watch(
    () => props.userId,
    (newUserId) => {
      if (newUserId && props.modelValue) {
        loadUserDetail()
      }
    },
    {immediate: true}
)

watch(
    () => props.modelValue,
    (newValue) => {
      if (newValue && props.userId) {
        loadUserDetail()
      }
    }
)
</script>

<style scoped>
/* 对话框样式 */
:deep(.user-detail-dialog) {
  border-radius: var(--admin-radius-lg);
  overflow: hidden;
}

:deep(.user-detail-dialog .el-dialog__header) {
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
  padding: var(--admin-space-lg);
}

:deep(.user-detail-dialog .el-dialog__title) {
  font-size: var(--admin-font-lg);
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
}

:deep(.user-detail-dialog .el-dialog__body) {
  padding: var(--admin-space-xl);
}

:deep(.user-detail-dialog .el-dialog__footer) {
  background: var(--admin-bg-secondary);
  border-top: 1px solid var(--admin-border-light);
  padding: var(--admin-space-lg);
}

.user-detail {
  min-height: 400px;
}

.user-header {
  display: flex;
  align-items: center;
  gap: var(--admin-space-lg);
  margin-bottom: var(--admin-space-xl);
  padding: var(--admin-space-xl);
  background: linear-gradient(135deg, var(--admin-bg-secondary), var(--admin-bg-tertiary));
  border-radius: var(--admin-radius-lg);
  border: 1px solid var(--admin-border-light);
  position: relative;
  overflow: hidden;
}

.user-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--admin-primary), var(--admin-primary-light));
}

.user-basic h3 {
  margin: 0 0 var(--admin-space-sm) 0;
  font-size: var(--admin-font-lg);
  color: var(--admin-text-primary);
  font-weight: var(--admin-font-semibold);
  line-height: var(--admin-line-height-sm);
}

.user-basic p {
  margin: 0 0 var(--admin-space-sm) 0;
  color: var(--admin-text-secondary);
  font-size: var(--admin-font-sm);
  font-weight: var(--admin-font-medium);
}

.detail-info {
  margin-top: var(--admin-space-lg);
}

.detail-info :deep(.el-descriptions) {
  border-radius: var(--admin-radius-md);
  overflow: hidden;
}

.detail-info :deep(.el-descriptions__header) {
  background: var(--admin-bg-secondary);
}

.detail-info :deep(.el-descriptions__body) {
  background: var(--admin-bg-primary);
}

.detail-info :deep(.el-descriptions__label) {
  background: var(--admin-bg-secondary);
  color: var(--admin-text-secondary);
  font-weight: var(--admin-font-medium);
}

.detail-info :deep(.el-descriptions__content) {
  color: var(--admin-text-primary);
  font-weight: var(--admin-font-medium);
}

.no-data {
  text-align: center;
  padding: var(--admin-space-xxl) 0;
  color: var(--admin-text-tertiary);
}

.dialog-footer {
  text-align: center;
  display: flex;
  justify-content: center;
  gap: var(--admin-space-md);
}

.dialog-footer .el-button {
  min-width: 120px;
  font-weight: var(--admin-font-medium);
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.user-detail-dialog) {
    width: 90vw !important;
    margin: var(--admin-space-md);
  }

  .user-header {
    flex-direction: column;
    text-align: center;
    gap: var(--admin-space-md);
  }

  .dialog-footer {
    flex-direction: column;
  }

  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>
